<template>
	<a-modal :centered="true" open title="智能巡检" width="660px" :body-style="{ padding: '40px 32px' }" @cancel="CloseModal">
		<div class="time">
			<a-form ref="formRef" :model="formState" :rules="rules" :label-col="{ span: 24 }" :wrapper-col="{ span: 24 }">
				<a-form-item label="摄像头轮换时间" name="rotationTime">
					<a-input-number v-model:value.trim="formState.rotationTime" :min="0" :max="99999" :precision="0" />
					<span style="line-height: 36px; color: #8b949e"> 秒</span>
				</a-form-item>
			</a-form>
		</div>
		<div class="account-data-permissions">
			<!-- 选择通道卡片 -->
			<a-card class="cards-item-left" :body-style="{ overflowY: 'scroll' }">
				<template #title>
					<span class="card-title font-14-bold">设备列表</span>
				</template>

				<a-input
					v-model:value.trim="searchValue"
					class="cards-input-search"
					placeholder="关键词"
					@press-enter="SearchTreeByInput(treeState)"
				>
					<template #prefix>
						<span class="iconfont icon-search-line" @click="SearchTreeByInput(treeState)"></span>
					</template>
				</a-input>
				<div></div>
				<a-tree
					v-model:expandedKeys="treeState.expandedKeys"
					v-model:selectedKeys="treeState.selectedKeys"
					v-model:checkedKeys="treeState.checkedKeys"
					class="left-tree"
					:auto-expand-parent="treeState.autoExpandParent"
					:field-names="{ children: 'children', title: 'name', key: 'id' }"
					:tree-data="treeState.treeData"
					:checkable="treeState.isshowchecked ? false : true"
					@check="CheckTreeNode"
				>
					<template #title="{ data, level, disabled }">
						<div class="tree-node-item" :style="{ color: disabled ? 'rgb(78, 89, 106)' : '#f0f6fc' }">
							<img
								v-if="Number(data.type) === 0"
								src="@/global-assets/svgs/camera-icon.svg"
								style="margin-top: 3px; margin-right: 8px; vertical-align: bottom"
							/>
							<span v-if="data.name.indexOf(searchValue) > -1">
								{{ data.name.substr(0, data.name.indexOf(searchValue)) }}
								<span class="font-14-bold">{{ searchValue }}</span>
								{{ data.name.substr(data.name.indexOf(searchValue) + searchValue.length) }}
							</span>
							<span v-else>{{ data.name }}</span>
						</div>
					</template>
				</a-tree>
			</a-card>
			<!-- 右侧卡片-->
			<a-card size="small" class="cards-item-right" style="height: 430px" :body-style="{ overflowY: 'scroll' }">
				<template #title>
					<span class="card-title">已选</span>
					<span style="font-weight: 400; color: #fff">{{ allDeviceList.selectedChild.length }} <i>/50</i> </span>
				</template>
				<div style="margin-top: 10px">
					<div :key="item.id" v-for="(item, index) in rightState.selectedList" class="select-item">
						<div style="width: 90%" class="select-text">{{ item.name }}</div>
						<div class="select-del" @click="SingleDelete(index, item)">
							<span class="iconfont icon-close-circle-fill" style="cursor: pointer"></span>
						</div>
					</div>
				</div>
				<template #extra><span class="empty ant-btn-link" style="cursor: pointer" @click="BatchDelete(treeState)">清空</span></template>
			</a-card>
		</div>
		<template #footer>
			<a-button size="small" class="btn-default" @click="CloseModal">取消</a-button>

			<a-button size="small" type="primary" :loading="loading" @click="FormSave">确定</a-button>
		</template>
	</a-modal>
</template>

<script setup lang="ts" name="InspectionDataPermissions">
import type { TreeProps, FormInstance } from 'ant-design-vue';
import { realVideoApi } from '../../api';
import type { Rule } from 'ant-design-vue/es/form';
import type { TsTreeState, TsRightList } from '../../type';
import { findSelectedNodes } from '../../utils';
const props = withDefaults(defineProps<{ screen: number }>(), {
	screen: 1
});
const emits = defineEmits<{
	(e: 'ok'): void;
	(e: 'close'): void;
}>();
const $message: any = inject('$message');
const formRef = ref<FormInstance>();
interface FormState {
	rotationTime: string;
}
const formState = reactive<FormState>({
	rotationTime: '30'
});
// 输入数字失焦时间
const rotationTimeReg = async (_rule: Rule, value: number): Promise<void> => {
	if (value < 30) {
		return Promise.reject('摄像头轮换时间不能低于30秒');
	}
	return Promise.resolve();
};
const rules: Record<string, Rule[]> = {
	rotationTime: [{ required: true, validator: rotationTimeReg }]
};
/*
1.新增 修改接口 deviceIdList =  treeState.checkedKeys

2.回显 只需要 把 formatRightSelectData(treeState.checkedKeys) 函数执行一次

3. 注意报错hooks 返回void 的类型定义

 */

const CloseModal = (): void => {
	emits('close');
};
interface TsSelectedList {
	id: string;
	name: string;
	type: number;
	children?: TsSelectedList[];
}
interface TsChild {
	selectedChild: [];
}
const allDeviceList = reactive<TsChild>({
	selectedChild: []
});
const loading = ref<boolean>(false);
// 树状态
const treeState = reactive<TsTreeState>({
	expandedKeys: [],
	selectedKeys: [],
	checkedKeys: [],
	treeData: [],
	flatTreeObj: {},
	autoExpandParent: false,
	isshowchecked: true
});

// 右侧列表状态
const rightState = reactive<TsRightList<TsSelectedList[]>>({
	selectedList: [],
	selectedKeys: []
});

const FormSave = async (): Promise<void> => {
	formRef.value
		?.validate()
		.then(async (): Promise<any> => {
			try {
				if (rightState.selectedList.length === 0) {
					$message.warning('至少需要选择1个摄像头才可以开启智能巡检');
					return;
				}
				if (allDeviceList.selectedChild.length > 50) {
					$message.warning('最多支持50路画面进行巡检，可以通过区域可进行批量选中或者取消，区域有半选状态');
					return;
				}
				loading.value = true;
				let screenNum: number = 1;
				console.log(props.screen, 'props.screen');
				screenNum = props.screen;
				// if (props.screen === 2) {
				// 	screenNum = 4;
				// }
				// if (props.screen === 3) {
				// 	screenNum = 9;
				// }
				let params = {
					rotationTime: formState.rotationTime,
					deviceIds: allDeviceList.selectedChild, // 如果是全选的话传全选的children
					screen: screenNum
				};
				let res: TsRes = await realVideoApi.saveInspection(params);
				if (res && res.code === 0) {
					$message.success('保存智能巡检信息成功');
					loading.value = false;
					emits('ok');
				} else {
					loading.value = false;
				}
			} catch (error) {
				loading.value = false;
				// eslint-disable-next-line promise/always-return
			} finally {
				//
			}
		})
		.catch((error: any) => {
			loading.value = false;
			console.log('表单提交验证错误', error);
		});
};
const checkNumber = (data: any): void => {
	data.forEach((ele: any) => {
		if (ele.children.length > 0) {
			checkNumber(ele.children);
		} else {
			if (!ele.disabled && ele.type === 0) {
				allDeviceList.selectedChild.push(ele as never);
			}
		}
	});
};
// 格式化右侧 keys ===> treeState.checkedKeys
const formatRightSelectData = (keys: string[]): void => {
	allDeviceList.selectedChild = [];
	rightState.selectedList = findSelectedNodes(treeState.treeData, keys).map(
		(key: string) => treeState.flatTreeObj[key]
	) as TsSelectedList[];
	checkNumber(rightState.selectedList);
};

// 是否自动展开父节点
const Code_Top = (): any => {
	const searchValue = ref();
	const SearchTreeByInput = (treeState: TsTreeState): void => {
		let expandKeys: (string | number)[] = [treeState.treeData[0].id];
		const tempFindFlags: Array<any> = [];

		if (searchValue.value) {
			for (const key in treeState.flatTreeObj) {
				const node = treeState.flatTreeObj[key];
				if (node.name.indexOf(searchValue.value) > -1) {
					tempFindFlags.push(toRaw(node));
				}
			}
			if (tempFindFlags.length) {
				tempFindFlags.forEach((node: Record<string, any>) => {
					!expandKeys.includes(node.parentId) && expandKeys.push(node.parentId);
				});
			} else {
				expandKeys = [treeState.treeData[0].key];
			}
		}
		treeState.expandedKeys = [...expandKeys];
	};

	return { searchValue, SearchTreeByInput };
};
const { searchValue, SearchTreeByInput } = Code_Top();

// 右侧已勾选的列表
const Code_RightCard = (): any => {
	const delSelectDevice = (treeInfo: TsSelectedList, ids: string[] = []): string[] => {
		ids.push(treeInfo.id);
		if (treeInfo.children && treeInfo.children.length) {
			treeInfo.children.forEach((item: TsSelectedList) => {
				ids.push(item.id);
				if (item.children && item.children.length) {
					delSelectDevice(item, ids);
				}
			});
		}
		return [...new Set(ids)];
	};

	// 单选删除
	const SingleDelete = (index: number, treeInfo: TsSelectedList): void => {
		delSelectDevice(treeInfo).forEach((item) => {
			treeState.checkedKeys.splice(
				treeState.checkedKeys.findIndex((delItem) => delItem === item),
				1
			);
			allDeviceList.selectedChild.splice(
				treeState.checkedKeys.findIndex((delItem) => delItem === item),
				1
			);
		});

		rightState.selectedList.splice(index, 1);
	};
	// 全选删除(清空)
	const BatchDelete = (treeState: TsTreeState): void => {
		rightState.selectedList = [];
		rightState.selectedKeys = [];
		allDeviceList.selectedChild = [];
		treeState.checkedKeys = [];
		treeState.selectedKeys = [];
	};

	return { rightState, SingleDelete, BatchDelete };
};
const { SingleDelete, BatchDelete } = Code_RightCard();

// 左侧通道Tree
const Code_LeftCard = (): any => {
	// 勾选Tree节点
	const CheckTreeNode = (checkedKeys: string[]): void => {
		formatRightSelectData(checkedKeys);
	};

	// 格式化Tree
	const formatTree = (dataList: TreeProps['treeData']) => {
		if (dataList) {
			for (const node of dataList) {
				// 节点添加选中属性

				if (Array.isArray(node.children) && node.children.length) {
					// 给节点的父级节点添加半选属性
					formatTree(node.children);
				} else {
					node.children = [];
				}
				treeState.flatTreeObj[node.id] = node;
			}
		}
	};

	const getPermissionData = async (): Promise<void> => {
		let res = await realVideoApi.getInspection();
		treeState.checkedKeys = res.data.ids;
		formatRightSelectData(treeState.checkedKeys as string[]);
	};

	const getTreeData = async (): Promise<void> => {
		const res: TsRes = await realVideoApi.tree();
		if (Array.isArray(res.data) && res.data.length) {
			treeState.treeData = [
				{
					id: '0',
					name: '全部',
					children: [...res.data]
				}
			];
			treeState.isshowchecked = false;
			// 默认展开
			treeState.expandedKeys = ['0'];
			treeState.flatTreeObj[0] = treeState.treeData[0];
			// 遍历格式化
			await formatTree(treeState.treeData[0].children);

			await getPermissionData();
		}
	};

	return { treeState, CheckTreeNode, getTreeData };
};
const { CheckTreeNode, getTreeData } = Code_LeftCard();

onMounted(async () => {
	getTreeData();
});
</script>

<style lang="less">
.time {
	margin-bottom: 32px;

	.ant-input-number {
		margin-right: 5px;
		border: 1px solid @mask02;
		border-radius: 6px;
		line-height: 36px;
		background: transparent !important;

		input {
			height: 36px;
		}
	}
}

.account-data-permissions {
	display: flex;
	padding: 40px 32px;
	align-items: center;

	.ant-tree-checkbox-inner {
		border-color: @mask02 !important;
		background-color: @mask01 !important;
	}

	.ant-tree-checkbox-checked {
		background-color: @primary01 !important;
	}

	:where(.css-dev-only-do-not-override-kqecok).ant-tree .ant-tree-switcher {
		position: relative;
		flex: none;
		align-self: center;
		width: 24px;
		margin: 0;
		line-height: 24px;
		text-align: center;
		cursor: pointer;
		user-select: none;
	}

	:where(.css-dev-only-do-not-override-kqecok).ant-tree .ant-tree-node-content-wrapper.ant-tree-node-selected,
	:where(.css-dev-only-do-not-override-kqecok).ant-tree .ant-tree-checkbox + span.ant-tree-node-selected {
		background-color: @background01 !important;
	}

	.ant-tree-treenode {
		line-height: 20px;
	}

	.left-tree {
		.tree-node-item {
			font-size: 12px;
			font-weight: 700;
			font-style: normal;
			line-height: 20px; /* 166.667% */
			color: @text01;
		}
	}

	.ant-card {
		background: @background02 !important;
	}

	.ant-card-head {
		min-height: 36px !important;
		border-bottom: 1px solid @borderColor02 !important;
		background: #101a2f !important;
	}

	.ant-tree-list-holder-inner {
		margin-left: -28px;
	}

	.ant-tree-list-holder-inner > div:first-child {
		margin-left: 48px;

		.ant-tree-switcher {
			display: none;
		}
	}

	.ant-tree-switcher {
		display: block;

		svg {
			color: #f0f6fc;
		}
	}

	.ant-tree {
		background-color: transparent !important;
	}

	.ant-tree-node-selected {
		background: none !important;
	}

	.cards-item-left {
		width: 304px;
		height: 430px;
		border: 1px solid @borderColor03 !important;
		border-top-right-radius: 0;
		border-bottom-right-radius: 0;

		.cards-input-search {
			width: 100%;
			height: 36px;
			margin-bottom: 13px;
			border: 1px solid @mask02;
			border-radius: 6px;
			font-size: 14px;
			font-weight: 400;
			background: transparent !important;

			.ant-input {
				color: @text03 !important;
				background-color: transparent !important;

				&::placeholder {
					color: @text04 !important;
				}
			}

			.icon-search-line {
				font-size: 14px;
				color: @text03;
				cursor: pointer;
			}
		}

		.ant-tree-treenode {
			margin-top: 5px;
		}

		.ant-tree-treenode-checkbox-checked > .ant-tree-node-content-wrapper {
			width: 244px;
			height: 24px;
			border-radius: 2px;
			// background: #d6e2f9;
		}

		.ant-card-head {
			// height: 20px;
			border: 0;
			padding: 0;
			color: @text02;
			background: #101a2f;

			.ant-card-head-title {
				border-bottom: 1px solid @borderColor02;
				padding: 3px 12px 6px;
				font-weight: 700;
			}
		}

		.ant-card-body {
			overflow: hidden;
			overflow-y: scroll;
			width: 300px;
			height: calc(100% - 40px);
			background: @background02;
		}
	}

	.ant-card-body {
		overflow: hidden;
		height: calc(100% - 40px);
		padding: 8px 8px 8px 12px;
	}

	.cards-item-right {
		width: 343px;
		height: 430px;
		border: 1px solid @borderColor02 !important;
		border-left: none !important;
		border-top-left-radius: 0;
		border-bottom-left-radius: 0;
		background: @background02;

		.card-title {
			margin-right: 5px;
			font-weight: 700;
			color: @text02;
		}

		span {
			i {
				font-style: normal;
				color: @text03;
			}
		}

		.select-item {
			justify-content: space-between;
			display: flex;
			margin-bottom: 10px !important;
			line-height: 22px;
			color: @text01;

			.select-text {
				overflow: hidden;
				width: value;
				line-height: 22px;
				white-space: nowrap;
				text-overflow: ellipsis;
				color: @text01;
			}

			.select-del {
				.iconfont {
					font-size: 14px;
					color: @text04;
				}
			}
		}
	}
}

.empty {
	color: #009cf8;
	cursor: pointer;
}
</style>
